package com.bizdk.generator.core.query;


import cn.hutool.core.util.StrUtil;
import com.bizdk.generator.core.DbType;

import java.util.StringJoiner;

/**
 * Oracle查询
 */
public class OracleQuery implements DialectQuery {

    @Override
    public DbType dbType() {
        return DbType.Oracle;
    }

    @Override
    public String tableSql(String tableName) {
        StringJoiner sql = new StringJoiner(" ");
        sql.add("select ") //
                .add("dt.table_name, ") //
                .add("dtc.comments ") //
                .add("from user_tables dt,user_tab_comments dtc ") //
                .add("where dt.table_name = dtc.table_name ");
        // 表名查询
        if (StrUtil.isNotBlank(tableName)) {
            sql.add("and dt.table_name = ' ").add(tableName).add("' ");
        }
        sql.add("order by dt.table_name asc ");
        return sql.toString();
    }

    @Override
    public String tableName() {
        return "table_name";
    }

    @Override
    public String tableComment() {
        return "comments";
    }

    @Override
    public String columnSql() {
        StringJoiner sql = new StringJoiner(" ");
        sql.add("SELECT ") //
                .add("A.COLUMN_NAME, ")  //
                .add("A.DATA_TYPE, ") //
                .add("B.COMMENTS, ") //
                .add("DECODE(C.POSITION, '1', 'PRI') KEY ") //
                .add("FROM ALL_TAB_COLUMNS A ") //
                .add("INNER JOIN ALL_COL_COMMENTS B ON A.TABLE_NAME = B.TABLE_NAME AND A.COLUMN_NAME = B.COLUMN_NAME AND B.OWNER = '#schema' ") //
                .add("LEFT JOIN ALL_CONSTRAINTS D ON D.TABLE_NAME = A.TABLE_NAME AND D.CONSTRAINT_TYPE = 'P' AND D.OWNER = '#schema'") //
                .add("LEFT JOIN ALL_CONS_COLUMNS C ON C.CONSTRAINT_NAME = D.CONSTRAINT_NAME AND C.COLUMN_NAME=A.COLUMN_NAME AND C.OWNER = '#schema'") //
                .add("WHERE A.OWNER = '#schema' AND A.TABLE_NAME = '%s' ORDER BY A.COLUMN_ID ");
        return sql.toString();
    }

    @Override
    public String columnName() {
        return "COLUMN_NAME";
    }


    @Override
    public String columnType() {
        return "DATA_TYPE";
    }


    @Override
    public String columnComment() {
        return "COMMENTS";
    }


    @Override
    public String columnKey() {
        return "KEY";
    }
}
